package org.geoscrape;

import java.util.ArrayList;
import java.util.Random;

import org.geoscrape.util.Tools;

/**
 * General tool for searching.
 *
 */
public class Searcher
{

	private ArrayList<SearchCallback> callbacks = new ArrayList<SearchCallback>();
	protected Login login;
	private int minSeconds;
	private int maxSeconds;
	private boolean useRandomdelay;
	private Random rand;
	
	public Searcher(Login login)
	{
		this.login = login;
	}


	/**
	 * Register a class that will receive a callback for all results as they
	 * come in.
	 * 
	 * @param callback
	 */
	public void registerSearchCallback(SearchCallback callback)
	{
		this.callbacks.add(callback);

	}

	public void unregisterSearchCallback(SearchCallback callback)
	{
		this.callbacks.remove(callback);
	}

	/**
	 * Announce that a new cache has been found to all callback listeners.
	 * @param c
	 */
	protected void announceCache(Cache c)
	{
		for (SearchCallback sc : callbacks)
		{
			sc.found(c);
		}
	}
	
	protected void announceCount(int count)
	{
		for(SearchCallback sc: callbacks)
		{
			sc.totalNumber(count);
		}
	}
	
	public void doRandomDelay()
	{
		if (isUseRandomDelay())
		{
			int range = maxSeconds - minSeconds;
			long sleep = rand.nextInt(range) + minSeconds;
			Tools.sleep(sleep);
		}
	}

	public void setMinSeconds(int minSeconds)
	{
		this.minSeconds = minSeconds;
	}

	public void setMaxSeconds(int maxSeconds)
	{
		this.maxSeconds = maxSeconds;
	}

	public void setUseRandomDelay(boolean b)
	{
		if (b && this.rand == null)
		{
			this.rand = new Random();
		}
		useRandomdelay = b;
	}

	public boolean isUseRandomDelay()
	{
		return this.useRandomdelay;
	}
}
